
//
//  JCViewWithXib.m
//  18Birdies
//
//  Created by James Chen on 15/6/30.
//  Copyright (c) 2015年 Lc. All rights reserved.
//

#import "CCViewWithXib.h"
#import <objc/runtime.h>
#import "LcFoundation.h"

@implementation CCViewWithXib

- (id)awakeAfterUsingCoder:(NSCoder*)aDecoder {
  if (self.subviews.count > 0) {
    return self;
  }
  UIView* view =
      [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:nil options:nil]
          objectAtIndex:0];
  LC_CHECK_TRUE(view.subviews.count > 0);
  view.frame = self.frame;
  view.autoresizingMask = self.autoresizingMask;
  view.translatesAutoresizingMaskIntoConstraints = self.translatesAutoresizingMaskIntoConstraints;

  for (NSLayoutConstraint* constraint in self.constraints) {
    if ([UIDevice currentDevice].systemVersion.floatValue < 10) {
      if (constraint.firstItem == self) {
        [constraint setValue:view forKey:@"firstItem"];
      }
      if (constraint.secondItem == self) {
        [constraint setValue:view forKey:@"secondItem"];
      }
    } else {
      Ivar referenceItem = class_getInstanceVariable(NSLayoutAnchor.class, "_referenceItem");
      id firstAnchorItem = object_getIvar([constraint valueForKey:@"firstAnchor"], referenceItem);
      if (firstAnchorItem == self) {
        object_setIvar([constraint valueForKey:@"firstAnchor"], referenceItem, view);
      }
      if ([constraint valueForKey:@"secondAnchor"] != nil) {
        id secondAnchorItem =
            object_getIvar([constraint valueForKey:@"secondAnchor"], referenceItem);
        if (secondAnchorItem == self) {
          object_setIvar([constraint valueForKey:@"secondAnchor"], referenceItem, view);
        }
      }
#ifdef DEBUG
      Ivar cachedReferenceItems =
          class_getInstanceVariable(NSLayoutAnchor.class, "_cachedReferenceItems");
      id cachedReferenceItemsValue =
          object_getIvar([constraint valueForKey:@"firstAnchor"], cachedReferenceItems);
      LC_CHECK_TRUE(cachedReferenceItemsValue == nil);
#endif
    }
  }

  for (UIView* subview in self.subviews) {
    [view addSubview:subview];
  }
  [view addConstraints:self.constraints];
  return view;
}

@end
